﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FriendlyURL.Web.UI.Helpers
{
    public enum UserRole : int
    {
        [StringValue("User")]
        User = 1,
        [StringValue("Owner")]
        Owner = 2,
        [StringValue("Administrator")]
        Administrator = 3
    }

    public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
                private readonly UserRole[] acceptedRoles;

        public CustomAuthorizeAttribute(params UserRole[] acceptedRoles)
        {
            this.acceptedRoles = acceptedRoles;
            ViewName = "Error";
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // Ensure user is authenticated before looking up user's roles
            if (!httpContext.Request.IsAuthenticated)
                return false;

            var rolesProvider = System.Web.Security.Roles.Providers["AccountRoleProvider"];

            string[] roles = rolesProvider.GetRolesForUser(httpContext.User.Identity.Name);

            foreach (UserRole role in this.acceptedRoles)
            {
                if (roles.Contains(role.GetStringValue(), StringComparer.OrdinalIgnoreCase))
                {
                    return true;
                }
            }

            return false;
        }

        /// <summary>
        ///   Gets or sets view name to render on authorization failure.  
        ///   Default is "UnauthorizedAccess".
        /// </summary>
        public string ViewName { get; set; }

        /// <summary>
        /// Processes HTTP requests that fail authorization.
        /// </summary>
        /// <param name = "filterContext">
        /// Encapsulates the information for using 
        /// <see cref = "T:System.Web.Mvc.AuthorizeAttribute" />. The 
        /// <paramref name = "filterContext" /> object contains the controller, 
        /// HTTP context, request context, action result, and route data.
        /// </param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.IsChildAction)
                base.HandleUnauthorizedRequest(filterContext);
            else
            {
                filterContext.Result = new HttpUnauthorizedWithRedirectResult
                {
                    ViewName = ViewName
                };
            }
        }
    }
}